/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.app.webcamwidgetca;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Queue;


import com.app.webcamwidgetca.R;

/**
 * Define a simple widget that shows the Wiktionary "Word of the day." To build
 * an update we spawn a background {@link Service} to perform the API queries.
 */
public class WordWidget extends AppWidgetProvider {

	public static final String AUTHORITY = "com.app.webcamwidgetca";
	public static final String PREFS_NAME = "PrefWidgetWebcam";
	private static String urlString;
	private static String filenameString;
	public static Bitmap bitmap;
	public static int idw;

	
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
    	
    	

     // Request update for these widgets and launch updater service
        context.startService(new Intent(context, UpdateService.class));

    }
    
    public static class UpdateService extends Service {
        


    	
    	@Override
        public void onStart(Intent intent, int startId) {
            
        	idw=0;
        	


        	
        	// Build the widget update for today
        	final Thread thread = new Thread(null, task, "webcamUpdate");
    		thread.start();      	
            
        }
        
        
        private final Runnable task = new Runnable() {
    		public void run() {
    			
    			
                
                // Push update for this widget to the home screen
                ComponentName thisWidget = new ComponentName(getApplicationContext(), WordWidget.class);
                AppWidgetManager manager = AppWidgetManager.getInstance(getApplicationContext());
               int [] appWidgetIds = manager.getAppWidgetIds(thisWidget);
                
            	for (int appWidgetId : appWidgetIds) {
                
            		//Uri appWidgetUri = ContentUris.withAppendedId(AppWidgets.CONTENT_URI, appWidgetId);
            		Uri appWidgetUri = ContentUris.withAppendedId(AppWidgets.CONTENT_URI, appWidgetId);
           		
                RemoteViews updateViews = buildUpdate(getApplicationContext(), appWidgetUri);
                //manager.updateAppWidget(thisWidget, updateViews);
                manager.updateAppWidget(appWidgetId, updateViews);
            	}
                
                UpdateService.this.stopSelf();
                }
        };
        /**
         * Build a widget update to show the current Wiktionary
         * "Word of the day." Will block until the online API returns.
         */
        public RemoteViews buildUpdate(Context context, Uri mAppWidgetUri) {
            // Pick out month names from resources
            Resources res = context.getResources();
            
            // Restore preferences
            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            urlString = settings.getString(mAppWidgetUri.toString(), "");
            filenameString = settings.getString(mAppWidgetUri.toString()+"f", "");

           
            RemoteViews updateViews = null;
            boolean imageOk = false;
            
            WordWidget.bitmap = null;
            String error = "";

            
            try {
            	// Try guetting the image        "http://www.woreic.com/"
            	URL url = new URL(urlString);
        		URLConnection connection = url.openConnection();
        		HttpURLConnection httpConnection = (HttpURLConnection) connection;
        		
        		if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
        		{
        			InputStream in = httpConnection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(in);
                    imageOk=true;
        		}		
            }
            catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    error += " No network";
                }
            
            //Si DL Ok je sauvegarde
            if (imageOk==true && filenameString!="") {
            	try {
                            FileOutputStream stream = super.openFileOutput(filenameString, MODE_PRIVATE);//mAppWidgetUri.toString()
                            
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                            stream.flush();
                            stream.close(); 
                    } catch (Exception e) {
                            e.printStackTrace();
                            error +=" No save";
                    }
            }
            //chargement de l'image
            bitmap = null;
            bitmap = BitmapFactory.decodeFile("/data/data/com.app.webcamwidgetca/files/"+filenameString);
                       
            if(bitmap!=null)
            {
            	// Build an update that holds the updated widget contents
                updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_image);
                updateViews.setImageViewBitmap(R.id.webcam, bitmap);//bitmap a def
                
            } else {
                // Didn't find word of day, so show error message
                updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_message);
                CharSequence errorMessage = context.getText(R.string.widget_error);
                if(urlString=="") updateViews.setTextViewText(R.id.message, "Click here to set up the url");//errorMessage);
                else updateViews.setTextViewText(R.id.message, errorMessage + error);//errorMessage);

            }
            
         // When user clicks on widget, launch to Wiktionary definition page
            //Intent defineIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString));
            Intent confIntent = new Intent(getApplicationContext(), Conf.class);
            confIntent.setData(mAppWidgetUri);

            PendingIntent pendingIntent = PendingIntent.getActivity(context,
                    0 /* no requestCode */, confIntent, 0 /* no flags */);
            updateViews.setOnClickPendingIntent(R.id.widget, pendingIntent);
            
            return updateViews;
        }
        

        
        
        
        @Override
        public IBinder onBind(Intent intent) {
            // We don't need to bind to this service
            return null;
        }
    }
    
    public static class AppWidgets  {
        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/appwidgets");

       
        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/appwidget";
        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/appwidget";

    }

}



